﻿#include "goodsmanagewidget.h"
#include "ui_goodsmanagewidget.h"

#include <QDebug>
#include <QMessageBox>
#include <string.h>
#include "SQLite.h"

GoodsManageWidget::GoodsManageWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GoodsManageWidget)
{
    ui->setupUi(this);

    connect(ui->codeEdit, SIGNAL(editingFinished()), this, SLOT(codeEditFinishedSlot()));
}

GoodsManageWidget::~GoodsManageWidget()
{
    delete ui;
}

void GoodsManageWidget::setPageKind(bool flag)
{
    this->isAddPage = flag;
}

Commodity GoodsManageWidget::getCmmodity()
{
    QByteArray tmp = ui->codeEdit->text().toLocal8Bit();
    char* id = tmp.data();
    QByteArray tmp2  = ui->nameEdit->text().toLocal8Bit();
    char* name = tmp2.data();
    double price = ui->priceSpinBox->value();

    Commodity comm;
    // 必须初始化数组为0，否则可能会有乱码
    memset(comm.id, 0, sizeof(comm.id));
    memset(comm.name, 0, sizeof(comm.name));
    memcpy(comm.id, id, strlen(id));
    memcpy(comm.name, name, strlen(name));
    comm.price = price;

    return comm;
}

void GoodsManageWidget::clearInfo()
{
    ui->codeEdit->setEnabled(true);
    ui->codeEdit->setText("");
    ui->nameEdit->setText("");
    ui->priceSpinBox->setValue(0.00);
}

void GoodsManageWidget::codeEditFinishedSlot()
{
    // 由于输入回车时会触发两次槽函数，所以如果光标还在codeEdit时，不触发函数，即不响应回车键
    if(ui->codeEdit->hasFocus()) return;
    qDebug() << "codeedit finished " << ui->codeEdit->text();
    QString id = ui->codeEdit->text();
    if(id == "")    return;
    Commodity* comm = new Commodity();
    int rcds = sqliteDB_opt_select_by_id(id.toLocal8Bit().data(), comm);
    if(isAddPage)
    {
        if(rcds)
        {
            QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("此编码的商品已存在"));
            this->clearInfo();
            return;
        }
    }
    else
    {
        if(rcds == 0)
        {
            QMessageBox::warning(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("此编码的商品不存在"));
            this->clearInfo();
            return;
        }
        else
        {
            ui->codeEdit->setEnabled(false);
            ui->nameEdit->setText(comm->name);
            ui->priceSpinBox->setValue(comm->price);
        }
    }
}
